package control;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import entities.tools.FilledForm;
import entities.tools.Form;
import entities.users.FormSigner;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import util.ejb.FilledFormBeanInterface;
import util.ejb.FormBeanInterface;
import util.ejb.FormSignerBeanInterface;

/**
 *
 * @author Marek
 */
@WebServlet(urlPatterns = {"/link.jsp"}, loadOnStartup=1)
@ServletSecurity(
        @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"admin"}))
public class LinkServlet extends AbstractServlet1 {

    @EJB
    FormBeanInterface formBean;
    @EJB
    FilledFormBeanInterface filledFormBean;
    @EJB
    FormSignerBeanInterface formSignerBean;

    public LinkServlet() {
    }

    @Override
    protected void construct(ServletConfig config, RegisterForms registerForms, RegisterActions registerActions) {
        config.setServletName("LinkServlet");
        config.setTemplateName("linkTmpl.jsp");

        registerForms.registerForm(LinkServlet.Keys.form.name(), FormKey.processFormOne);
        registerActions.registerAction(Keys.delete.name(), ActionKey.processActionOne);
    }

    @Override
    protected void initSesionVars(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, BreakProcessException, RedirectRequest {
        Form form = formBean.getExistingForm(new Long(1));

        if (null == form) {
            throw new ServletException("LinkServlet->initSessionVars(): Form (id=1) doesn't exist in the database.");
        }

        List<FilledForm> lastlyCreatedFilledForms = filledFormBean.getLastlyCreatedFilledForms(form, 100);
        session.setAttribute(Keys.lastlyCreatedFilledForms.name(), lastlyCreatedFilledForms);
        session.setAttribute(Keys.form.name(), form);
    }

    @Override
    protected void load(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, IOException, BreakProcessException, RedirectRequest {
     
    }

    @Override
    protected void save(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, IOException, BreakProcessException, RedirectRequest {
     
    }

    public enum Keys {

        form,
        questions,
        formSigner,
        linkHash,
        filledForm,
        lastlyCreatedFilledForms,
        delete
    }
    /*
     if (null != session.getAttribute("getParamDelete")) {
     Long filledFormId = new Long((String) session.getAttribute("getParamDelete"));
     filledFormBean.deleteFilledForm(filledFormBean.getFilledForm(filledFormId));
     }
     if (null != session.getAttribute("getParamGenerate") && session.getAttribute("getParamGenerate").equals("true")) {
     Map<String, String[]> requestParameters = request.getParameterMap();
     if (requestParameters.containsKey("firstName")
     && requestParameters.containsKey("secondName")
     && requestParameters.containsKey("phone")
     && requestParameters.containsKey("email")) {
     String firstName = new String(requestParameters.get("firstName")[0].getBytes("iso-8859-1"), "UTF-8");
     String secondName = new String(requestParameters.get("secondName")[0].getBytes("iso-8859-1"), "UTF-8");
     String phone = new String(requestParameters.get("phone")[0].getBytes("iso-8859-1"), "UTF-8");
     String email = new String(requestParameters.get("email")[0].getBytes("iso-8859-1"), "UTF-8");

     FormSigner formSigner = formSignerBean.getFormSigner(firstName, secondName, phone, email);
     if (null == formSigner) {
     formSigner = formSignerBean.createFormSigner();
     formSigner.setFirstName(firstName);
     formSigner.setSecondName(secondName);
     formSigner.setPhone(phone);
     formSigner.setEmail(email);
     formSignerBean.updateFormSigner(formSigner);
     }
     FilledForm filledForm = filledFormBean.createFilledForm();
     String toBeHashed = filledForm.getId() + formSigner.getId() + formSigner.getFirstName() + formSigner.getSecondName() + formSigner.getPhone() + formSigner.getEmail() + filledForm.getWhenCreated().toString();
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(toBeHashed.getBytes(), 0, toBeHashed.length());
     String linkHash = (new BigInteger(1, md.digest()).toString(16));

     filledForm.setLinkHash(linkHash);
     filledForm.setForm(form);
     filledForm.setFormSigner(formSigner);
     filledFormBean.updateFilledForm(filledForm);

     String generatedFormUrl = request.getRequestURL().toString().replaceAll("/link.jsp", "");
     generatedFormUrl += "/form.jsp?linkHash=" + linkHash;

     session.setAttribute("generatedFormUrl", generatedFormUrl);

     //get last 100 filledForms inner join to formSigner ordered by creationDate desc and save it to the map of strings  
     } else {
     session.setAttribute("generatedFormUrl", "");
     }
     }
     List<FilledForm> lastlyCreatedFilledForms = filledFormBean.getLastlyCreatedFilledForms(form, 100);
     session.setAttribute("lastlyCreatedFilledForms", lastlyCreatedFilledForms);
     request.getRequestDispatcher("WEB-INF/linkTmpl.jsp").include(request, response);
     } catch (NoSuchAlgorithmException ex) {
     Logger.getLogger(LinkServlet.class.getName()).log(Level.SEVERE, null, ex);
     ex.printStackTrace();
     }
     }*/

    @Override
    protected void processFormOne(HttpSession session, RegisterParameter parameters, RegisterError errors) throws ServletException, IOException, BreakProcessException, RedirectRequest {
        try {
            Form form = (Form) session.getAttribute(Keys.form.name());
            session.setAttribute(Keys.lastlyCreatedFilledForms.name(), filledFormBean.getLastlyCreatedFilledForms(form, 100));
            if (parameters.doParameterExist("firstName")
                    && parameters.doParameterExist("secondName")
                    && parameters.doParameterExist("phone")
                    && parameters.doParameterExist("email")) {
                String firstName = parameters.readParameter("firstName")[0];
                String secondName = parameters.readParameter("secondName")[0];
                String phone = parameters.readParameter("phone")[0];
                String email = parameters.readParameter("email")[0];

                FormSigner formSigner = this.formSignerBean.getFormSigner(firstName, secondName, phone, email);
                if (null == formSigner) {
                    formSigner = formSignerBean.createFormSigner();
                    formSigner.setFirstName(firstName);
                    formSigner.setSecondName(secondName);
                    formSigner.setPhone(phone);
                    formSigner.setEmail(email);
                    formSignerBean.updateFormSigner(formSigner);
                }
                FilledForm filledForm = filledFormBean.createFilledForm();
                String toBeHashed = filledForm.getId() + formSigner.getId() + formSigner.getFirstName() + formSigner.getSecondName() + formSigner.getPhone() + formSigner.getEmail() + filledForm.getWhenCreated().toString();
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(toBeHashed.getBytes(), 0, toBeHashed.length());
                String linkHash = (new BigInteger(1, md.digest()).toString(16));

                filledForm.setLinkHash(linkHash);
                filledForm.setForm(form);
                filledForm.setFormSigner(formSigner);
                filledFormBean.updateFilledForm(filledForm);

                session.setAttribute(Keys.lastlyCreatedFilledForms.name(), filledFormBean.getLastlyCreatedFilledForms(form, 100));
                //String generatedFormUrl = request.getRequestURL().toString().replaceAll("/link.jsp", "");
                //generatedFormUrl += "/form.jsp?linkHash=" + linkHash;
                //session.setAttribute("generatedFormUrl", generatedFormUrl);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("LinkServlet->processFormOne: " + e.getMessage());
        }
    }

    @Override
    protected void processActionOne(HttpSession session,RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest {
        try {
            Long filledFormId = new Long(params.readParameter("attribute1")[0]);
            filledFormBean.deleteFilledForm(filledFormBean.getFilledForm(filledFormId));
        } catch (Exception e) {

        }
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    /*    @Override
     protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     try (PrintWriter out = response.getWriter()) {
     /* TODO output your page here. You may use following sample code. */
    /*
     Form form = formBean.getExistingForm(new Long(1));
     if (null == form) {
     out.println("");
     return;
     }
     session.setAttribute("form", form);

     if (null != session.getAttribute("getParamDelete")) {
     Long filledFormId = new Long((String) session.getAttribute("getParamDelete"));
     filledFormBean.deleteFilledForm(filledFormBean.getFilledForm(filledFormId));
     }
     if (null != session.getAttribute("getParamGenerate") && session.getAttribute("getParamGenerate").equals("true")) {
     Map<String, String[]> requestParameters = request.getParameterMap();
     if (requestParameters.containsKey("firstName")
     && requestParameters.containsKey("secondName")
     && requestParameters.containsKey("phone")
     && requestParameters.containsKey("email")) {
     String firstName = new String(requestParameters.get("firstName")[0].getBytes("iso-8859-1"), "UTF-8");
     String secondName = new String(requestParameters.get("secondName")[0].getBytes("iso-8859-1"), "UTF-8");
     String phone = new String(requestParameters.get("phone")[0].getBytes("iso-8859-1"), "UTF-8");
     String email = new String(requestParameters.get("email")[0].getBytes("iso-8859-1"), "UTF-8");

     FormSigner formSigner = formSignerBean.getFormSigner(firstName, secondName, phone, email);
     if (null == formSigner) {
     formSigner = formSignerBean.createFormSigner();
     formSigner.setFirstName(firstName);
     formSigner.setSecondName(secondName);
     formSigner.setPhone(phone);
     formSigner.setEmail(email);
     formSignerBean.updateFormSigner(formSigner);
     }
     FilledForm filledForm = filledFormBean.createFilledForm();
     String toBeHashed = filledForm.getId() + formSigner.getId() + formSigner.getFirstName() + formSigner.getSecondName() + formSigner.getPhone() + formSigner.getEmail() + filledForm.getWhenCreated().toString();
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(toBeHashed.getBytes(), 0, toBeHashed.length());
     String linkHash = (new BigInteger(1, md.digest()).toString(16));

     filledForm.setLinkHash(linkHash);
     filledForm.setForm(form);
     filledForm.setFormSigner(formSigner);
     filledFormBean.updateFilledForm(filledForm);

     String generatedFormUrl = request.getRequestURL().toString().replaceAll("/link.jsp", "");
     generatedFormUrl += "/form.jsp?linkHash=" + linkHash;

     session.setAttribute("generatedFormUrl", generatedFormUrl);

     //get last 100 filledForms inner join to formSigner ordered by creationDate desc and save it to the map of strings  
     } else {
     session.setAttribute("generatedFormUrl", "");
     }
     }
     List<FilledForm> lastlyCreatedFilledForms = filledFormBean.getLastlyCreatedFilledForms(form, 100);
     session.setAttribute("lastlyCreatedFilledForms", lastlyCreatedFilledForms);
     request.getRequestDispatcher("WEB-INF/linkTmpl.jsp").include(request, response);
     } catch (NoSuchAlgorithmException ex) {
     Logger.getLogger(LinkServlet.class.getName()).log(Level.SEVERE, null, ex);
     ex.printStackTrace();
     }
     }*/
    
    @Override
    protected void beforeExit(HttpSession session, RegisterParameter registerParam, RegisterError registerError) {
        session.removeAttribute(Keys.lastlyCreatedFilledForms.name());
        session.removeAttribute(Keys.form.name());
    }
}
